#include "convert.h"
#include "xdebug.h"

iconv_t 
convert_open(const char *from, const char *to)
{
    iconv_t cd;

    cd = iconv_open(to, from);
    
    return cd;
}

int     
convert(iconv_t cd, char* save, int savelen, char *src, int srclen)
{
    char   *inbuf = src;
    char *outbuf = save;
    size_t outbufsize = savelen;
    int status = 0;
    size_t  savesize = 0;
    size_t inbufsize = srclen;
    const char* inptr = inbuf;
    size_t      insize = inbufsize;
    char* outptr = outbuf;
    size_t outsize = outbufsize;


    iconv(cd,NULL,NULL,NULL,NULL);
    if (inbufsize == 0) {
        status = -1;
        goto done;
    }
    INFO("insize: %d\n", insize);
    while (insize > 0) {
        size_t res = iconv(cd,(ICONV_CONST char**)&inptr,&insize,&outptr,&outsize);
        if (outptr != outbuf) {
            int saved_errno = errno;
            int outsize = outptr - outbuf;
            strncpy(save+savesize, outbuf, outsize);
            errno = saved_errno;
        }
        INFO("convert: %d, insize: %d,%s\n", res, insize, save);

        // res 是已经转换的字节
        if (res == (size_t)(-1)) {
            INFO("errno: %d\n", errno);
            if (errno == EILSEQ) {
                int one = 1;
                iconvctl(cd,ICONV_SET_DISCARD_ILSEQ,&one);
                status = -3;
            } else if (errno == EINVAL) {
                if (inbufsize == 0) {
                    status = -4;
                    goto done;
                } else {
                    break;
                }
            } else if (errno == E2BIG) {
                status = -5;
                goto done;
            } else {
                status = -6;
                goto done;
            }
        }
    }
    INFO("size: %d, %s\n", strlen(save), save);
    status = strlen(save);
done:
    return status;
  
}

void    
convert_close(iconv_t cd)
{
    iconv_close(cd);
}

int     
convert_string(const char *from, const char *to, char *dst, int dstlen, char *src, int srclen)
{
    iconv_t     cd;
    int         ret;

    cd = convert_open(from, to);
    if ((int)cd == -1) {
        return -1;
    }  
    ret = convert(cd, dst, dstlen, src, srclen);

    convert_close(cd);
    return ret;
}




